package com.edais.service.imp;

import com.edais.dao.TurnOutDao;
import com.edais.service.TurnOutService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.StringUtil;
import com.edais.vo.CouponVo;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultConstant;
import com.yunzhi.domain.ResultDTO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
@Service

public class TurnOutServiceImpl implements TurnOutService{
	
	private static final Log logger=LogFactory.getLog(TurnOutServiceImpl.class);
	@Autowired
	private TurnOutDao turnOutdao;
	@Override
	public ResultDTO queryTurnOutList(Map<String, Object> map) throws Exception {
		ResultDTO result;
		// 调用核心接口E390004
	  	String transCode = "E390004";
		String jsonStr = CommonUtil.constructJsonStr(transCode,String.valueOf(map.get("userId")),map);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		List<Map<String,String>> retList=new ArrayList<Map<String,String>>();

		if(Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))){
			String totalNum = jsonObject.get("totalNum").toString();
			JSONArray jsonArr = jsonObject.getJSONArray("list");
			int pageSize=Integer.parseInt(String.valueOf(map.get(Consts.Page.PAGE_SIZE_NAME)));
			result = new ResultDTO(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getMsg(),
					ResultCode.SUCCESS.getType(),pageSize,Integer.parseInt(totalNum),jsonArr);
		} else {
			result=new ResultDTO(ResultCode.FAILED);
			logger.error("=====E390004核心接口调用异常=====");
			logger.error("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
		}
		return result;
	}
	@Override
	public ResultDTO queryCouponList(Map<String, Object> parms) throws Exception {
		
		Map<String,String> map=new HashMap<>();
		map.put("rowBegin", (String)parms.get("rowBegin"));
		map.put("rowEnd", (String)parms.get("rowEnd"));
		map.put("userId", (String)parms.get("userId"));
		map.put("status", (String)parms.get("status"));
		map.put("current", (String)parms.get("current"));
		map.put("pageSize", (String)parms.get("pageSize"));

		String total= turnOutdao.getCouponListSize(map);
		int totalSize=Integer.parseInt(total);
		int pageSize=Integer.parseInt(map.get(Consts.Page.PAGE_SIZE_NAME));

		if (totalSize <= 0) {
			return ResultConstant.SUCCESS;
		}
		List<CouponVo> couponList = turnOutdao.getCouponList(map);
		return new ResultDTO(ResultCode.SUCCESS, pageSize, totalSize, couponList);

	}
	/***
	 * 查询活期的7天折线图，本金收益和日期
	 */
	@Override
	public ResultDTO getmoneyUserId(Map<String, Object> parmMap) throws Exception {
		ResultDTO resultDTO ;
		String transCode = "E390015";
		String userId = (String) parmMap.get("userId");
		parmMap.put("userId", userId);
		parmMap.put("dayNum", parmMap.get("dayNum"));
		String dayNum=(String)parmMap.get("dayNum");
		if(dayNum==null||StringUtils.isBlank(dayNum)){
			dayNum="7";
		}
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();//查询结果一个json的字符串
		//Map<String, Object> resultMap = new HashMap<String, Object>();//查询结果一个json的字符串
		if(StringUtil.isEmpty(userId+"") || "null".equals(userId+"")){
			Map<String, Object> amountMap=null;
			Map<String,Map<String, Object>> map=null;
			Calendar cal=Calendar.getInstance();
			SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
			map=new TreeMap<String,Map<String, Object>>();//使用TreeMap用作排序,默认升序
			for (int i = 0; i < 7; i++) {
				amountMap=new HashMap<String,Object>();
				amountMap.put("investAmount", "0.00");
				amountMap.put("incomeAmount", "0.00");
				amountMap.put("totalRise", "0.00");
				cal.setTime(new Date());
				cal.add(Calendar.DATE,-(i+1));
				Date date1=cal.getTime();
				String sss1=sim.format(date1);
				amountMap.put("incomeDay", sss1);
				map.put(sss1, amountMap);
			}

			resultDTO = new ResultDTO(ResultCode.SUCCESS);
			resultDTO.setRecords(new ArrayList());

		}
		// 构建json字符串
		String jsonStr = CommonUtil.constructJsonStr(transCode, null, parmMap);
		// 调用核心接口
		String rtnStr = CommonUtil.getCoreValue(jsonStr);
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		if(Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))){
			JSONArray jsonArr = jsonObject.getJSONArray("list");
			Map<String, Object> amountMap=null;
			//
			Map<String,Map<String, Object>> map=null;
			Calendar cal=Calendar.getInstance();
			SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
			map=new TreeMap<String,Map<String, Object>>();//使用TreeMap用作排序,默认升序
			for (int i = 0; i < Integer.parseInt(dayNum); i++) {
				amountMap=new HashMap<String,Object>();
				amountMap.put("investAmount", "0.00");
				amountMap.put("incomeAmount", "0.00");
				amountMap.put("totalRise", "0.00");
				cal.setTime(new Date());
				cal.add(Calendar.DATE,-(i+1));
				Date date1=cal.getTime();
				String sss1=sim.format(date1);
				amountMap.put("incomeDay", sss1);
				map.put(sss1, amountMap);
			}
			if(jsonArr != null && jsonArr.size() > 0){
				for(int i = 0; i < jsonArr.size(); i++){
					JSONObject jsonObj = jsonArr.getJSONObject(i);
					amountMap=new HashMap<String,Object>();
					amountMap.put("investAmount", jsonObj.getString("investAmount"));
					amountMap.put("incomeAmount", jsonObj.getString("incomeAmount"));
					amountMap.put("totalRise",jsonObj.getString("totalRise"));
					amountMap.put("incomeDay", jsonObj.getString("incomeDay"));
					map.put(jsonObj.getString("incomeDay"), amountMap);
				}
			}
			for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
				String key = (String) iterator.next();
				resultList.add(map.get(key));
			}
			resultDTO = new ResultDTO(ResultCode.SUCCESS);
			resultDTO.setRecords(resultList);
		} else {
			logger.error("=====E390015核心接口调用异常=====");
			logger.error("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
			resultDTO = new ResultDTO(ResultCode.FAILED);
			resultDTO.setRecords(new ArrayList());
		}

		JSONObject jsonTodayInvestNum = new JSONObject();
		jsonTodayInvestNum.put("todayInvestNum",jsonObject.getString("todayInvestNum"));
		resultDTO.setRecord(jsonTodayInvestNum);
		// 设置返回code
		return resultDTO;
	}

	/**
	 * 历史收益和年化收益率
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public ResultDTO queryAmountStatementList(Map<String, Object> map)
			throws Exception {
		// 调用核心接口E390015
		String transCode = "E390015";
		Map<String, Object> parmMap = new HashMap<String, Object>();
		parmMap.put("userId", map.get("userId"));
		parmMap.put("dayNum", "1");//随便给个值
		parmMap.put("flag", map.get("flag"));
		String pageSize = (String) map.get(Consts.Page.PAGE_SIZE_NAME);//页码
		String current = (String) map.get(Consts.Page.PAGE_CURRENT_NAME);//每页行数
		if (pageSize == null || StringUtils.isBlank(pageSize) || "0".equals(pageSize)) {
			pageSize = "10";
		}
		if (current == null || StringUtils.isBlank(current) || "0".equals(current)) {
			current = "1";
		}
		int beginNum = (Integer.parseInt(current) - 1) * Integer.parseInt(pageSize) + 1;
		int endNum = Integer.parseInt(pageSize) * Integer.parseInt(current);

		parmMap.put("rowBegin", String.valueOf(beginNum));
		parmMap.put("rowEnd", String.valueOf(endNum));
		String jsonStr = CommonUtil.constructJsonStr(transCode, map.get("userId").toString(), parmMap);
		String rtnStr = CommonUtil.getCoreValue(jsonStr);//请求核心
		//返回数据JOSN格式
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();//查询结果一个json的字符串
		Map<String, Object> resultMap = new HashMap<String, Object>();//查询结果一个json的字符串
		JSONObject jsonObject = JSONObject.fromObject(rtnStr);
		if (Consts.SUCCESS_CODE.equals(jsonObject.get("rescode"))) {
			JSONArray jsonArr = jsonObject.getJSONArray("list");
			if (jsonArr != null && jsonArr.size() > 0) {
				Map<String, Object> amountMap = null;
				for (int i = 0; i < jsonArr.size(); i++) {
					JSONObject jsonObj = jsonArr.getJSONObject(i);
					amountMap = new HashMap<String, Object>();
					amountMap.put("investAmount", jsonObj.getString("investAmount"));
					amountMap.put("incomeAmount", jsonObj.getString("incomeAmount"));
					amountMap.put("totalRise", jsonObj.getString("totalRise"));
					amountMap.put("incomeDay", jsonObj.getString("incomeDay"));
					resultList.add(amountMap);
				}

				ResultDTO resultDTO = new ResultDTO(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getMsg(),ResultCode.SUCCESS.getType(),
						Integer.parseInt(pageSize),jsonObject.getInt("totalNum"),resultList);
				JSONObject jsonO = new JSONObject();
				jsonO.put("totalIncomeAmount",jsonObject.getString("totalIncomeAmount"));
				jsonO.put("currentValue",jsonObject.getString("currentValue"));
				resultDTO.setRecord(jsonO);
				return resultDTO;
			} else {
				logger.info("=====E390015核心接口查询为空=====");
				ResultDTO resultDTO = new ResultDTO(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getMsg(),ResultCode.SUCCESS.getType(),
						Integer.parseInt(pageSize),0,new ArrayList());
				JSONObject jsonO = new JSONObject();
				jsonO.put("totalIncomeAmount",jsonObject.getString("totalIncomeAmount"));
				jsonO.put("currentValue",jsonObject.getString("currentValue"));
				resultDTO.setRecord(jsonO);
				return resultDTO;
			}

		} else {
			logger.error("=====E390015核心接口调用异常=====");
			logger.error("rescode：" + jsonObject.getString("rescode") + "；  resmsg：" + jsonObject.getString("resmsg"));
			ResultDTO resultDTO = new ResultDTO(ResultCode.SUCCESS.getCode(),ResultCode.SUCCESS.getMsg(),ResultCode.SUCCESS.getType(),
					Integer.parseInt(pageSize),0,new ArrayList());
			JSONObject jsonO = new JSONObject();
			jsonO.put("totalIncomeAmount","0");
			jsonO.put("currentValue","0");
			resultDTO.setRecord(jsonO);
			return resultDTO;
		}
	}
}

